package com.dianrui.fmi.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import android.widget.ListView;
import android.widget.TextView;

import com.dianrui.fmi.Constant;
import com.dianrui.fmi.R;
import com.dianrui.fmi.event.AddOptionalStock;
import com.dianrui.fmi.event.RfreshIndex;
import com.dianrui.fmi.util.CountDownTimerUtils;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.dianrui.fmi.view.MyListView;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


public class KLineActivity extends BaseActivity {
    private String starttime, symbol, names, fullsymbol, highs, lows, opens, ycs, types, symbold, price, zf, zc;
    private String buy1s, buy2s, positions, servicechagres;
    private String type;
    private long ticks;
    private Map<String, String> mMap = new HashMap<>();
    private List<String> symbolList = new ArrayList<>();


    @BindView(R.id.show_price)
    TextView showPrices;
    @BindView(R.id.zf)
    TextView zfs;
    @BindView(R.id.zd)
    TextView zds;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.webview)
    WebView webView;
    @BindView(R.id.zf_img)
    ImageView zfImg;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.buy)
    Button buy;
    @BindView(R.id.sell)
    Button sell;

    @BindView(R.id.kline_show_info_layout)
    LinearLayout klineShowInfoLayout;
    @BindView(R.id.bid_ask)
    TextView bidAsk;
    @BindView(R.id.day_range)
    TextView dayRange;
    @BindView(R.id.fiftytwowk)
    TextView fiftytwowk;
    @BindView(R.id.previous_close)
    TextView previousClose;
    @BindView(R.id.open_txt)
    TextView openTxt;
    @BindView(R.id.month_txt)
    TextView monthTxt;
    @BindView(R.id.last_tradingday)
    TextView lastTradingday;
    @BindView(R.id.group)
    TextView group;
    @BindView(R.id.one_year_change_txt)
    TextView oneYearChangeTxt;

    @BindView(R.id.overview_txt)
    TextView overviewTxt;
    @BindView(R.id.technical_txt)
    TextView technicalTxt;
    @BindView(R.id.News_txt)
    TextView NewsTxt;
    @BindView(R.id.analysis_txt)
    TextView analysisTxt;

    @BindView(R.id.news_list)
    MyListView newsList;
    @BindView(R.id.analysis_list)
    MyListView analysisList;

    @BindView(R.id.technical_list)
    ListView technicalList;


    @BindView(R.id.technical_list_layout)
    LinearLayout technicalListLayout;
    @BindView(R.id.news_list_layout)
    LinearLayout newsListLayout;
    @BindView(R.id.analysis_list_layout)
    LinearLayout analysisListLayout;

    @BindView(R.id.show_price_layout)
    LinearLayout showPriceLayout;


    @Override
    public int getContentViewId() {
        return R.layout.activity_kline;
    }

    @SuppressLint({"SetJavaScriptEnabled", "SetTextI18n", "ClickableViewAccessibility"})
    @Override
    public void initView() {
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            names = bundle.getString("name");
            ticks = bundle.getLong("tick");
            types = bundle.getString("type");
            symbold = bundle.getString("symbold");
            starttime = bundle.getString("starttime");
            symbol = bundle.getString("symbol");
            opens = bundle.getString("open");
            ycs = bundle.getString("yc");
            fullsymbol = bundle.getString("fullsymbol");
            price = bundle.getString("price");
            highs = bundle.getString("high");
            lows = bundle.getString("low");
            zf = bundle.getString("zf");
            zc = bundle.getString("zc");
            buy1s = bundle.getString("buy1");
            buy2s = bundle.getString("buy2");
            positions = bundle.getString("position");
            servicechagres = bundle.getString("servicecharge");
            type=bundle.getString("type");
        }
        title.setText(fullsymbol);
        openTxt.setText(opens);
        lastTradingday.setText(MyUtil.stampToDate(ticks));
        bidAsk.setText(buy2s + "/" + buy1s);
        dayRange.setText(buy2s + "/" + buy1s);
        fiftytwowk.setText(lows + "-" + highs);
        group.setText(types);
        monthTxt.setText(MyUtil.stampToDates(ticks));


        webView.loadUrl(Constant.kline_url+fullsymbol);
        WebSettings webSetting = webView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setDomStorageEnabled(true);
        webView.setWebViewClient(new AreaWebClient());
        getDetails();

        detailsTimer.start();
    }

    @SuppressLint("SetTextI18n")
    private void getDetails() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("symbol", fullsymbol);
        OkHttpUtils.getInstance().postWithMemberToken(Url.MARKERDETAILS, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (symbolList != null) {
                                    symbolList.clear();
                                }
                                String fullSymbol = jsonObject.optJSONObject("data").optString("full_symbol");
                                symbolList.add(fullSymbol);
                                showPrices.setText(jsonObject.optJSONObject("data").optString("price"));
                                buy.setText(getString(R.string.buys) + " " + jsonObject.optJSONObject("data").optString("buy1"));
                                sell.setText(getString(R.string.sell) + " " + jsonObject.optJSONObject("data").optString("buy2"));
                                if (!StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("tick"))) {
                                    long l = jsonObject.optJSONObject("data").optLong("tick");
                                    String dates = new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date(l * 1000));
                                    time.setText(dates);
                                }
                                if (!StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("zd"))) {
                                    zds.setText(MyUtil.formatBy2double(Double.valueOf(jsonObject.optJSONObject("data").optString("zd")), 3));
                                }
                                if (!StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("zf"))) {
                                    zfs.setText("(" + jsonObject.optJSONObject("data").optString("zf") + "%" + ")");
                                }
                                if (jsonObject.optJSONObject("data").optString("zf").contains("-")) {
                                    showPrices.setTextColor(getResources().getColor(R.color.green_2ab23c));
                                    zfs.setTextColor(getResources().getColor(R.color.green_2ab23c));
                                    zds.setTextColor(getResources().getColor(R.color.green_2ab23c));
                                    zfImg.setImageResource(R.mipmap.green_arrow_down);
                                } else {
                                    showPrices.setTextColor(getResources().getColor(R.color.red1));
                                    zfs.setTextColor(getResources().getColor(R.color.red1));
                                    zds.setTextColor(getResources().getColor(R.color.red1));
                                    zfImg.setImageResource(R.mipmap.arrow_up_red);
                                }
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void Save() {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < symbolList.size(); i++) {
            jsonArray.put(symbolList.get(i));
        }
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("is_del", "0");
            jsonObject.put("symbol_list", jsonArray);
            OkHttpUtils.getInstance().postWithMemberToken(Url.SAVEOPTIONAL, jsonObject.toString(),  new OkHttpUtils.XCallBack() {

                @Override
                public void onResponse(String result) {
                    if (!StringUtils.isEmpty(result)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject && !isFinishing()) {
                                if ("1000".equals(jsonObject.optString("status"))) {
                                    ToastUtil.showToast(getString(R.string.add_success));
                                    EventBus.getDefault().post(new RfreshIndex());
                                    EventBus.getDefault().post(new AddOptionalStock());
                                    finish();
                                } else {
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    CountDownTimerUtils detailsTimer = new CountDownTimerUtils(Long.MAX_VALUE, 5000) {
        @Override
        public void onTick(long millisUntilFinished) {
            getDetails();
        }

        @Override
        public void onFinish() {
        }
    };

    class AreaWebClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            webView.loadUrl(url);
            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                view.loadUrl(request.getUrl().toString());
            } else {
                view.loadUrl(request.toString());
            }
            return true;
        }


            @Override
        public void onPageFinished(WebView view, String url) {


        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) webView.getLayoutParams();
            WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels;
            int height = dm.heightPixels;
            params.width = width;
            params.height = height -700;
            view.setLayoutParams(params);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }


    }

    @OnClick({R.id.back, R.id.top_right, R.id.buy, R.id.sell, R.id.overview_layout, R.id.technical_layout, R.id.news_layout, R.id.analysis_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.top_right:
                Save();
                break;
            case R.id.overview_layout://overview
                overviewTxt.setTextColor(getResources().getColor(R.color.white));
                technicalTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                NewsTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                analysisTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                webView.setVisibility(View.VISIBLE);
                buy.setVisibility(View.VISIBLE);
                sell.setVisibility(View.VISIBLE);
                klineShowInfoLayout.setVisibility(View.VISIBLE);
                technicalListLayout.setVisibility(View.GONE);
                newsListLayout.setVisibility(View.GONE);
                analysisListLayout.setVisibility(View.GONE);
                break;

            case R.id.technical_layout://Technical
                overviewTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                technicalTxt.setTextColor(getResources().getColor(R.color.white));
                NewsTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                analysisTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                webView.setVisibility(View.GONE);
                buy.setVisibility(View.GONE);
                sell.setVisibility(View.GONE);
                klineShowInfoLayout.setVisibility(View.GONE);
                technicalListLayout.setVisibility(View.VISIBLE);
                newsListLayout.setVisibility(View.GONE);
                analysisListLayout.setVisibility(View.GONE);

                break;

            case R.id.news_layout://News
                overviewTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                technicalTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                NewsTxt.setTextColor(getResources().getColor(R.color.white));
                analysisTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                webView.setVisibility(View.GONE);
                buy.setVisibility(View.GONE);
                sell.setVisibility(View.GONE);
                klineShowInfoLayout.setVisibility(View.GONE);
                technicalListLayout.setVisibility(View.GONE);
                newsListLayout.setVisibility(View.VISIBLE);
                analysisListLayout.setVisibility(View.GONE);

                break;

            case R.id.analysis_layout://analysis
                overviewTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                technicalTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                NewsTxt.setTextColor(getResources().getColor(R.color.gray_afafaf));
                analysisTxt.setTextColor(getResources().getColor(R.color.white));
                webView.setVisibility(View.GONE);
                buy.setVisibility(View.GONE);
                sell.setVisibility(View.GONE);
                klineShowInfoLayout.setVisibility(View.GONE);
                technicalListLayout.setVisibility(View.GONE);
                newsListLayout.setVisibility(View.GONE);
                analysisListLayout.setVisibility(View.VISIBLE);
                break;

            case R.id.back:
                if (detailsTimer != null) {
                    detailsTimer.cancel();
                }
                finish();
                break;

            case R.id.buy:
                Intent intent = new Intent(KLineActivity.this, OrderActivity.class);
                Bundle bundle = new Bundle();
                bundle.putLong("tick", ticks);
                bundle.putString("symbold", symbold);
                bundle.putString("direction", "1");
                bundle.putString("type", type);
                bundle.putString("fullsymbol", fullsymbol);
                bundle.putString("buy1", buy1s);
                bundle.putString("buy2", buy2s);
                bundle.putString("position", positions);
                bundle.putString("servicecharge", servicechagres);
                bundle.putString("price", price);
                bundle.putString("high", highs);
                bundle.putString("low", lows);
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
                break;

            case R.id.sell:
                Intent intent1 = new Intent(KLineActivity.this, OrderActivity.class);
                Bundle bundle1 = new Bundle();
                bundle1.putLong("tick", ticks);
                bundle1.putString("symbold", symbold);
                bundle1.putString("direction", "2");
                bundle1.putString("fullsymbol", fullsymbol);
                bundle1.putString("buy1", buy1s);
                bundle1.putString("buy2", buy2s);
                bundle1.putString("type", type);
                bundle1.putString("position", positions);
                bundle1.putString("servicecharge", servicechagres);
                bundle1.putString("price", price);
                bundle1.putString("high", highs);
                bundle1.putString("low", lows);
                intent1.putExtras(bundle1);
                startActivity(intent1);
                finish();
                break;

            default:
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (detailsTimer != null) {
                detailsTimer.cancel();
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.clearCache(true);
            webView.stopLoading();
            //防止系统在3.x的手机，在缩放按钮未完全关闭时候退出的闪退
            webView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (webView != null) {
                        webView.destroy();
                        webView = null;
                    }
                }
            }, 3000);
        }
        super.onDestroy();
    }
}
